<?php
class ExcelWriterComponent extends Object{

	function startup(& $controller) {
		$this->controller = & $controller;
	}

	function createExcel($values_col,$header_col=null,$file_name='filename',$name_list=null,$col_key=null) {

		vendor('Excel/Writer');
		
		set_time_limit(3600);
	
		// Creating a workbook
		$workbook = new Spreadsheet_Excel_Writer();
		$workbook->setVersion(8);
		
		// sending HTTP headers
		$workbook->send($file_name.'.xls');
		$workbook->setCustomColor(12, 255, 255, 99);
		
		$format_title =& $workbook->addFormat();
		$format_title->setBold();

		$format_title->setFgColor(12);
//		$format_title->setFgColor('light yellow');
		
		// Creating a worksheet
		$worksheet =& $workbook->addWorksheet($file_name);
		$worksheet->setInputEncoding('utf-8');
		
		// The actual data
		
		if(!empty($header_col) || is_array($header_col)){

			if(!empty($col_key)|| is_array($col_key)){
				$foreach_keys = $col_key;
			}else{
				$foreach_keys = array_keys($header_col);
			}
			
			foreach($foreach_keys as $pos_y=>$foreach_key){
				$worksheet->write(0, $pos_y, $header_col[$foreach_key],$format_title);
			}

		}
		
		if(!empty($values_col) || is_array($values_col)){

			if(!empty($col_key)|| is_array($col_key)){
				$foreach_keys = $col_key;
			}elseif(!empty($header_col) || is_array($header_col)){
				$foreach_keys = array_keys($header_col);
			}

			foreach($values_col as $_pos_x => $value_col_tmp){
				if(!empty($header_col) || is_array($header_col)){
					$pos_x = $_pos_x + 1;
				}else{
					$pos_x = $_pos_x;
				}
				$value_col = array();
				foreach($value_col_tmp as $value_col_tmp_val){
					foreach($value_col_tmp_val as $value_col_tmp2_key=>$value_col_tmp2_val){
						$value_col[$value_col_tmp2_key] = $value_col_tmp2_val;
					}
				}
				if(empty($foreach_keys)){
					$foreach_keys = array_keys($value_col);
				}
				foreach($foreach_keys as $pos_y=>$foreach_key){
					if(!empty($name_list)|| is_array($name_list)){
						$worksheet->write($pos_x, $pos_y, $this->getStringValue($value_col,$foreach_key,$name_list));
					}else{
						if(isset($value_col[$foreach_key])){
							$worksheet->write($pos_x, $pos_y, $value_col[$foreach_key]);							
						}
					}
				}
			}	
		}
				
		// Let's send the file
		$workbook->close();
		
		set_time_limit(30);
		
}

	function getStringValue($value_col,$foreach_key,$name_list){
		if(isset($name_list[$foreach_key]) || !empty($name_list[$foreach_key])){
			$list = $name_list[$foreach_key];
			$value = $value_col[$foreach_key];
			
			$value_split = explode(',',$value);
			$name_split = array();
			if(!empty($value_split)){
				foreach($value_split as $value){
					if(isset($list[$value])){
						$name_split[] = $list[$value];
					}
				}
			}
			return implode(',',$name_split);
		}else{
			return $value_col[$foreach_key];
		}
	}

}
?>